package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.AttrAttrgroupRelationService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrRespVo;
import com.atguigu.gulimall.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.service.AttrService;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Resource
    AttrAttrgroupRelationDao attrgroupRelationDao;

    @Resource
    AttrGroupDao attrGroupDao;

    @Resource
    CategoryDao categoryDao;

    @Autowired
    CategoryService categoryService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveAttrVo(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        //复制相同属性的属性值
        BeanUtils.copyProperties(attrVo, attrEntity);
        //本身的dao插入数据
        baseMapper.insert(attrEntity);
        //中间表插入数据来记录属性所属的分组关系
        Long attrGroupId = attrVo.getAttrGroupId();
        if (!StringUtils.isEmpty(attrGroupId)) {
            //基本属性往中间表中插入数据
            AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
            entity.setAttrGroupId(attrVo.getAttrGroupId());
            entity.setAttrId(attrEntity.getAttrId());
            entity.setAttrSort(0);
            attrgroupRelationDao.insert(entity);
        }

    }

    @Override
    public PageUtils queryCatGroup(Map<String, Object> params, long catId, String type) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        //修改查询的逻辑：查询的时候要携带上属性的类型去查询
        wrapper.eq("attr_type", type.equalsIgnoreCase("base") ? 1 : 0);

        //按照分类编号去查
        if (catId != 0) {
            wrapper.eq("catelog_id", catId);
        }
        //如果含有检索条件的话(模糊查询)，拼接检索条件，支持attr_id=key or attr_name like key
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((obj) -> {
                obj.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        //由于响应的结果不完整，将响应的数据重新组装为AttrRespVo，并且将缺失的字段在Vo中返回。
        //在项目中，禁止使用多表联查，所以通过stream来组装数据
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> voList = records.stream().map((attrEntity -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            //复制属性
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            //查询到中间表的数据
            AttrAttrgroupRelationEntity relationEntity = attrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attrEntity.getAttrId()));

            if (!(relationEntity == null)) {
                Long attrGroupId = relationEntity.getAttrGroupId();
                //避免空指针
                if (attrGroupId != null) {
                    //查询所属分组
                    AttrGroupEntity groupEntity = attrGroupDao.selectById(attrGroupId);
                    //设置分组名称
                    attrRespVo.setGroupName(groupEntity.getAttrGroupName());
                }

            }
            //设置三级分类的名称
            Long catelogId = attrEntity.getCatelogId();
            if (catelogId != null) {
                CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
                //设置分类的名称
                attrRespVo.setCatelogName(categoryEntity.getName());
            }

            return attrRespVo;
        })).collect(Collectors.toList());
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(voList);
        return pageUtils;
    }

    @Override
    public AttrRespVo getAttrDetail(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        AttrEntity attrEntity = baseMapper.selectById(attrId);
//        QueryWrapper<AttrAttrgroupRelationEntity> wrapper = new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId);
//    //查询中间表的数据
//        AttrAttrgroupRelationEntity relationEntity = attrgroupRelationDao.selectOne(wrapper);
//        relationEntity.get
        Long catelogId = attrEntity.getCatelogId();
        Long[] catelogFullPath = categoryService.getCatelogFullPath(catelogId);
        BeanUtils.copyProperties(attrEntity, attrRespVo);
        attrRespVo.setCatelogPath(catelogFullPath);
        return attrRespVo;
    }



    @Override
    public void updateAttrInfo(AttrVo attr) {
        //基本数据的更新
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        baseMapper.updateById(attrEntity);
        Long attrGroupId = attr.getAttrGroupId();
        if (!StringUtils.isEmpty(attrGroupId)) {
            //不为空，说明是基本属性的更新，则要去更新中间表
            //查询中间表的数据
            Integer count = attrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attr.getAttrId()));
            if (count > 0) {
                //存在就更新
                AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
                relationEntity.setAttrId(attr.getAttrId());
                relationEntity.setAttrGroupId(attr.getAttrGroupId());
                attrgroupRelationDao.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_id", attr.getAttrId()));
            } else {
                //做新增操作
                AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
                relationEntity.setAttrSort(1);
                relationEntity.setAttrId(attr.getAttrId());
                relationEntity.setAttrGroupId(attr.getAttrGroupId());
                attrgroupRelationDao.insert(relationEntity);
            }
        }


    }



    @Override
    public PageUtils getNoRelation(Map<String, Object> params, Long attrgroupId) {
        //查询当前分组可以绑定的属性(未被其他分组所引用)
        //查询当前分组所绑定的分类catId
        //查询catId都拥有哪些分组ID
        //查询分组ID都绑定了哪些属性
        //在当前分类中剔除掉这些属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        //获取分类的编号
        Long catelogId = attrGroupEntity.getCatelogId();
        //查询当前分类拥有哪些分组
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("catelog_id",catelogId);
        List<AttrGroupEntity> attrGroupEntities = attrGroupDao.selectList(wrapper);
        //分组编号
        List<Long> attrGroupIds = attrGroupEntities.stream().map((item) -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());


        QueryWrapper<AttrAttrgroupRelationEntity> wrapper1 = new QueryWrapper<>();

        if (attrGroupIds!=null&&attrGroupIds.size()>0){
            wrapper1.in("attr_group_id",attrGroupIds);
        }
        //查询这些分组绑定的所有的属性编号
        List<AttrAttrgroupRelationEntity> relationEntities = attrgroupRelationDao.selectList(wrapper1);

        List<Long> collect = relationEntities.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        //在当前分类的属性中移除这些属性
        //模糊查询
        QueryWrapper<AttrEntity> attrWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        //只展示基础属性
        if (!StringUtils.isEmpty(key)){
            attrWrapper.and((item)->{
                item.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        attrWrapper.eq("attr_type",1l).eq("catelog_id",catelogId);
        //属性编号的非空判断
        if (collect!=null&&collect.size()>0){
            attrWrapper.notIn("attr_id",collect);
        }

        //组装分页查询
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), attrWrapper);
        return new PageUtils(page);
    }


}